<template>
  <div style="width: 100%; margin-left: 10px">
    <titleNav info="我的配件库"></titleNav>
    <div style="margin-top: 10px">
      配件编号：<el-input
        v-model="pageForm.partNo"
        style="width: 20%"
      ></el-input>
      负责人：<el-input v-model="pageForm.leader" style="width: 20%"></el-input>
      配件名称：<el-input
        v-model="pageForm.partName"
        style="width: 20%"
      ></el-input>
      <el-button @click="getEquipmentList">查询</el-button>
    </div>
    <el-button type="danger" @click="addEquip">新增配件</el-button>
    <el-button type="info" @click="uploadDiavissable = true">导入</el-button>
    <el-button type="warning" @click="exportDiavissable = true">导出</el-button>
    <el-button type="danger" @click="muilDelete" :disabled="!muiltForm"
      >批量删除</el-button
    >
    <el-table
      :data="EquipList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="partNo" label="配件编号" width="180" />
      <el-table-column prop="partName" label="配件名称" width="180" />
      <el-table-column prop="partType" label="配件类型" width="180" />
      <el-table-column prop="partNumber" label="配件型号" width="180" />
      <el-table-column prop="number" label="剩余数量" width="180" />
      <el-table-column prop="backNumber" label="待归还数量" width="180" />
      <el-table-column prop="updateTime" label="最后更新时间" width="180" />

      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button @click="subMitUpdate(scope.row)">修改</el-button>
          <el-button @click="subMitdelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageForm.pageNum"
      v-model:page-size="pageForm.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="updateDiavissable" title="修改配件信息">
      <el-form :model="updateForm">
        <el-form-item label="配件编号"
          ><el-input v-model="updateForm.partNo" disabled></el-input
        ></el-form-item>
        <el-form-item label="配件数量"
          ><el-input v-model="updateForm.number"></el-input
        ></el-form-item>
        <el-form-item label="待归还数量"
          ><el-input v-model="updateForm.backNumber"></el-input
        ></el-form-item>
        <el-form-item label="配件型号"
          ><el-input v-model="updateForm.partNumber"></el-input
        ></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateDiavissable = false">取消</el-button>
        <el-button @click="suresubMitUpdate">确定</el-button>
      </template>
    </el-dialog>
    <!-- 删除对话框 -->
    <el-dialog v-model="deleteDiavissable" title="删除配件">
      <span>您确定要删除此配件吗？</span>
      <template #footer>
        <el-button @click="deleteDiavissable = false">取消</el-button>
        <el-button @click="suresubMitdelete">确定</el-button>
      </template>
    </el-dialog>
    <!-- 增加对话框 -->
    <el-dialog v-model="addDiavissable" title="增加配件">
      <el-form ref="ruleFormRef" :model="addForm" :rules="rules">
        <el-form-item label="配件编号" prop="partNo"
          ><el-input
            v-model="addForm.partNo"
            placeholder="编号不可重复"
            type="number"
          ></el-input
        ></el-form-item>
        <el-form-item label="配件名称" prop="partName"
          ><el-input v-model="addForm.partName"></el-input
        ></el-form-item>
        <el-form-item label="配件类型" prop="partType">
          <el-input v-model="addForm.partType"></el-input>
        </el-form-item>
        <el-form-item label="配件型号" prop="partNumber">
          <el-input v-model="addForm.partNumber"></el-input>
        </el-form-item>
        <el-form-item label="配件数量" prop="number">
          <el-input v-model="addForm.number"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="addForm.leader"></el-input>
        </el-form-item>
        <el-form-item label="条形码名称" prop="barCode">
          <el-input v-model="addForm.barCode"></el-input>
        </el-form-item>
        <el-form-item label="二维码名称" prop="twoCode">
          <el-input v-model="addForm.twoCode"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDiavissable = false">取消</el-button>
        <el-button @click="suresubMitAdd(ruleFormRef)">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="uploadDiavissable">
      <el-upload
        class="upload-demo"
        drag
        action="http://jacs2.zhihuifenban.com/system/part/import"
        :headers="customHeaders"
        :on-success="handleSuccess"
      >
        <el-icon class="el-icon--upload"><i-ep-upload-Filled /></el-icon>
        <div class="el-upload__text">拖拽上传或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">一次只能上传一份文件</div>
        </template>
      </el-upload>
    </el-dialog>
    <!-- 导出确认 -->
    <el-dialog v-model="exportDiavissable">
      <el-button @click="sureExportPart">确定</el-button>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, ref, reactive } from 'vue'
import {
  getEquipList,
  updatePart,
  deletePart,
  addPart,
  exportPart
} from '@/api/baseUrl12'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user.js'
import { download } from '@/utils/requestDianjian'
const userStore = useUserStore()

const EquipList = ref([])
// 分页处理（传给后端处理）
const size = ref('default')
const pageForm = ref({
  pageSize: '10',
  partName: '',
  partNo: '',
  leader: '',
  pageNum: '1'
})
const total = ref('')
const handleSizeChange = (val) => {
  //控制分页
  console.log(val)
  pageForm.value.pageSize = val
  pageForm.value.pageNum = '1'
  getEquipmentList()
}
const handleCurrentChange = (val) => {
  pageForm.value.pageNum = val
  getEquipmentList()
}
const getEquipmentList = async () => {
  const res = await getEquipList(pageForm.value)
  total.value = res.total
  EquipList.value = res.rows
}
const updateDiavissable = ref(false)
const updateForm = ref()

// 修改配件信息
const subMitUpdate = (row) => {
  updateForm.value = row
  updateDiavissable.value = true
  console.log(updateForm.value)
}
const suresubMitUpdate = async () => {
  const res = await updatePart(updateForm.value)
  if (res.code == 200) {
    ElMessage({
      message: '修改成功',
      type: 'success'
    })
    getEquipmentList()
    updateDiavissable.value = false
  } else {
    ElMessage({
      message: '未知错误，请联系管理员',
      type: 'error'
    })
  }
}
// 删除配件
const deleteDiavissable = ref(false)
const muiltForm = ref()
const muilDelete = () => {
  deleteDiavissable.value = true
}
const handleSelectionChange = (val) => {
  muiltForm.value = ''
  muiltForm.value = muiltForm.value.concat(val.map((item) => item.partId))
  console.log(muiltForm.value)
}
const subMitdelete = (row) => {
  muiltForm.value = row.partId
  deleteDiavissable.value = true
}

const suresubMitdelete = async () => {
  const res = await deletePart({ partId: muiltForm.value })
  if (res.code == 200) {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    getEquipmentList()
    updateDiavissable.value = false
  } else {
    ElMessage({
      message: res.msg,
      type: 'error'
    })
  }
}
// 添加配件
const addForm = ref({
  partNo: null, // 配件编号
  partName: '', // 配件名称
  partType: '', // 配件类型
  partNumber: '', // 配件型号
  number: null, // 库存数量
  backNumber: 0, // 待归还数量
  leader: '', // 负责人
  barCode: '', // 条形码名称
  twoCode: '' // 二维码名称
})
const addDiavissable = ref(false)
const addEquip = () => {
  addDiavissable.value = true
}
const ruleFormRef = ref()
const rules = reactive({
  partNo: [{ required: true, message: '请输入配件编号', trigger: 'blur' }],
  partName: [{ required: true, message: '请输入配件名称', trigger: 'blur' }],
  partType: [{ required: true, message: '请输入配件类型', trigger: 'blur' }],
  partNumber: [{ required: true, message: '请输入配件型号', trigger: 'blur' }],
  number: [{ required: true, message: '请输入配件数量', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  barCode: [{ required: true, message: '请输入条形码名称', trigger: 'blur' }],
  twoCode: [{ required: true, message: '请输入二维码名称', trigger: 'blur' }]
  // 其他字段的规则
})
const suresubMitAdd = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      addForm.value.partNo = Number(addForm.value.partNo)
      addForm.value.number = Number(addForm.value.number)
      const res = await addPart(addForm.value)
      console.log(res)
      if (res.code == 200) {
        ElMessage({
          message: '增加成功',
          type: 'success'
        })
        getEquipmentList()
        addDiavissable.value = false
      } else if (res.code == 500) {
        ElMessage({
          message: res.msg,
          type: 'error'
        })
      } else {
        ElMessage({
          message: '未知错误，请联系管理员',
          type: 'error'
        })
      }
    } else {
      const messages = Object.values(fields)
        .flatMap((errorArray) => {
          return errorArray.map((error) => error.message)
        })
        .join('，') // 使
      ElMessage({
        message: messages,
        type: 'error'
      })
      console.log('error submit!', fields)
    }
  })
}
// 上传文件配置
const uploadDiavissable = ref(false)
const customHeaders = ref({
  authorization: userStore.userInfo.token
})
const handleSuccess = (response, file) => {
  console.log('上传成功，服务器响应:', response)
  console.log('上传的文件信息:', file)

  // 你可以在这里处理响应数据，例如显示消息
  ElMessage({
    message: '文件上传成功',
    type: 'success'
  })
}

//导出文件配置
const exportForm = ref({
  leader: '',
  partIds: [],
  sysPart: {}
})
// 导出文件
const exportDiavissable = ref(false)
const sureExportPart = async () => {
  // const res = await exportPart(exportForm.value)
  // console.log(res)
  download(
    'system/part/export',
    {
      // ...this.queryParams
    },
    `job_${new Date().getTime()}.xlsx`
  )
}

onMounted(() => {
  getEquipmentList()
})
</script>
<style lang="less" scoped>
.el-icon--upload {
  font-size: 40px !important;
}
</style>
